package com.dhp.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dhp.annotation.AuthCheck;
import com.dhp.common.BaseResponse;
import com.dhp.common.DeleteRequest;
import com.dhp.common.ErrorCode;
import com.dhp.common.ResultUtils;
import com.dhp.constant.UserConstant;
import com.dhp.exception.BusinessException;
import com.dhp.model.dto.chart.ChartAddRequest;
import com.dhp.model.dto.chart.ChartGenRequest;
import com.dhp.model.dto.chart.ChartQueryRequest;
import com.dhp.model.dto.chart.ChartUpdateRequest;
import com.dhp.model.entity.Chart;
import com.dhp.model.entity.ChartData;
import com.dhp.model.entity.User;
import com.dhp.model.vo.GenChartVO;
import com.dhp.service.ChartDataService;
import com.dhp.service.ChartService;
import com.dhp.service.UserService;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 帖子接口
 *
 * @author dhp
 */
@RestController
@RequestMapping("/chart")
@Slf4j
public class ChartController {

    @Resource
    private ChartService chartService;

    @Resource
    private UserService userService;


    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ChartDataService chartDataService;


    // region 增删改查

    /**
     * 创建
     *
     * @param chartAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addchart(@RequestBody ChartAddRequest chartAddRequest, HttpServletRequest request) {
        if (chartAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = new Chart();
        BeanUtils.copyProperties(chartAddRequest, chart);
        // 校验
        chartService.validChart(chart, true);
        User loginUser = userService.getLoginUser(request);
        chart.setUserId(loginUser.getId());
        boolean result = chartService.save(chart);
        if (!result) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        long newchartId = chart.getId();
        return ResultUtils.success(newchartId);
    }



    /**
     * 更新
     *
     * @param chartUpdateRequest
     * @param request
     * @return
     */
    @PostMapping("/update")
    public BaseResponse<Boolean> updatechart(@RequestBody ChartUpdateRequest chartUpdateRequest,
                                            HttpServletRequest request) {
        if (chartUpdateRequest == null || chartUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = new Chart();
        BeanUtils.copyProperties(chartUpdateRequest, chart);
        // 参数校验
        chartService.validChart(chart, false);
        User user = userService.getLoginUser(request);
        long id = chartUpdateRequest.getId();
        // 判断是否存在
        Chart oldchart = chartService.getById(id);
        if (oldchart == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 仅本人或管理员可修改
        if (!oldchart.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = chartService.updateById(chart);
        return ResultUtils.success(result);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping ("/delete")
    @Transactional
    public BaseResponse<Boolean> deletechart(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Chart oldchart = chartService.getById(id);
        QueryWrapper<ChartData> queryWrapper = new QueryWrapper<>();

        if (oldchart == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 仅本人或管理员可删除
        if (!oldchart.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }

        boolean b = chartService.removeById(id);
        queryWrapper.eq("chartId" , oldchart.getId());
        boolean remove = chartDataService.remove(queryWrapper);

        //如果删除成功更新redis中的信息
        if (remove && b){
            Gson gson = new Gson();
            String key = UserConstant.CHART_KEY_PRE + userService.getLoginUser(request).getId();
            QueryWrapper<Chart> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("userId" , user.getId());
            List<Chart> list = chartService.list(queryWrapper1);
            String JsonStr = gson.toJson(list);
            redisTemplate.opsForValue().set(key , JsonStr);
        }

        return ResultUtils.success(b && remove);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<Chart> getchartById(long id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = chartService.getById(id);
        return ResultUtils.success(chart);
    }

    /**
     * 获取列表（仅管理员可使用）
     *
     * @param chartQueryRequest
     * @return
     */
    @AuthCheck(mustRole = "admin")
    @GetMapping("/list")
    public BaseResponse<List<Chart>> listchart(ChartQueryRequest chartQueryRequest) {
        Chart chartQuery = new Chart();
        if (chartQueryRequest != null) {
            BeanUtils.copyProperties(chartQueryRequest, chartQuery);
        }
        QueryWrapper<Chart> queryWrapper = new QueryWrapper<>(chartQuery);
        List<Chart> chartList = chartService.list(queryWrapper);
        return ResultUtils.success(chartList);
    }

    @PostMapping("/my/list/page")
    public BaseResponse<Page<Chart>> listMyChart(@RequestBody ChartQueryRequest chartQueryRequest , HttpServletRequest request){
        if (BeanUtil.isEmpty(chartQueryRequest)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR , "请求参数为空");
        }

        Page<Chart> page = chartService.listMyChart(chartQueryRequest , request);
        return ResultUtils.success(page);
    }


    /**
     * 生成图表
     * @param file
     * @param chartGenRequest
     * @param request
     * @return
     */
    @PostMapping("/gen")
    public BaseResponse<GenChartVO> genChartByAI(@RequestParam("file")MultipartFile file , ChartGenRequest chartGenRequest , HttpServletRequest request){
        if (file == null || BeanUtil.isEmpty(chartGenRequest)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR , "参数为空");
        }
        //处理文件，获取向AI提问信息
        GenChartVO res = chartService.genChartByAI(file , chartGenRequest , request);
        return ResultUtils.success(res);
    }

    /**
     * 异步生成图表
     * @param file
     * @param chartGenRequest
     * @param request
     * @return
     */
    @PostMapping("/gen/async")
    public BaseResponse<GenChartVO> genChartByAIAsync(@RequestParam("file")MultipartFile file , ChartGenRequest chartGenRequest , HttpServletRequest request){
        if (file == null || BeanUtil.isEmpty(chartGenRequest)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR , "参数为空");
        }
        //处理文件，获取向AI提问信息
        GenChartVO res = chartService.genChartByAIAsync(file , chartGenRequest , request);
        return ResultUtils.success(res);
    }

}
